# -*- coding: utf-8 -*-
import requests
import json
import logging

from app.config import Config
from app.db.database import SessionLocal
from app.db.crud import create_tjudge, update_tpost_is_judge
from app.dify.tag_saver import TagSaver
from app.monitor import status_manager

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


class LLMWithOutJina:
    def __init__(self, post_id: int, content: str, url: str):
        self.post_id = post_id
        self.content = content
        self.url = url
        config = Config()
        self.judge_url = config.llm_without_jina_url
        self.api_key = config.llm_without_jina_api_key

    def run_workflow(self) -> bool:
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

        # 请求体
        data = {
            "inputs": {
                "input_text": self.content
            },
            "response_mode": "blocking",  # 或者 "streaming"
            "user": "unique_user_id",  # 替换为实际的用户标识
            "files": []  # 如果需要上传文件，可以在这里添加文件信息
        }
        # data = {
        #     "inputs": {
        #         "input_url": "https://www.baidu.com/s?wd=%E8%8B%B1%E4%BC%9F%E8%BE%BE%E5%B8%82%E5%80%BC%E4%B8%80%E5%A4%9C%E8%92%B8%E5%8F%916400%E4%BA%BF%E5%85%83"
        #     },
        #     "response_mode": "blocking",  # 或者 "streaming"
        #     "user": "unique_user_id",  # 替换为实际的用户标识
        #     "files": []  # 如果需要上传文件，可以在这里添加文件信息
        # }

        # 发送 POST 请求
        response = requests.post(self.judge_url, headers=headers, data=json.dumps(data))

        # 检查响应状态码
        if response.status_code == 200:
            # 解析响应内容
            # 返回样例 {'task_id': '777043cd-1c95-486f-ad8a-edf9faea5f6f', 'workflow_run_id': 'c7d445fa-bf29-4243-9f92-76b6216d94a9',
            #  'data': {'id': 'c7d445fa-bf29-4243-9f92-76b6216d94a9', 'workflow_id': 'f87ee74a-de04-40c4-9afc-31bb6e279fb8',
            #           'status': 'succeeded',
            #           'outputs': {'text': '{\n"散布焦虑": 7,\n"知识密集程度": 5,\n"乐观程度": 3,\n"质量评分": 4,\n"类别": "财经"\n}'}, 'error': None,
            #           'elapsed_time': 6.64927216101205, 'total_tokens': 3540, 'total_steps': 4, 'created_at': 1733813051,
            #           'finished_at': 1733813058}}
            response_data = response.json()

            # 记录原始响应
            logger.info(f"[LLM Response for Post {self.post_id}]")
            logger.info(f"Raw response: {json.dumps(response_data, ensure_ascii=False, indent=2)}")

            # 1. 获取 outputs 字段
            outputs = response_data['data']['outputs']

            # 2. 解析 outputs 中的 text 字段
            text_content = outputs['text']
            try:
                # 预处理文本内容
                text_content = text_content.strip()
                
                # 记录处理前的内容
                logger.info(f"Raw text content before processing: {repr(text_content)}")
                
                # 检查是否是有效的 JSON 开始
                if not text_content.startswith('{'):
                    logger.error(f"Invalid JSON format, content does not start with '{{': {text_content}")
                    return False

                # 尝试直接解析
                try:
                    parsed_data = json.loads(text_content)
                except json.JSONDecodeError as je:
                    logger.error(f"Initial JSON parsing failed: {str(je)}")
                    
                    # 尝试修复常见的编码问题
                    try:
                        # 确保文本是UTF-8编码
                        text_content = text_content.encode('utf-8').decode('utf-8')
                        # 移除可能的BOM标记
                        if text_content.startswith('\ufeff'):
                            text_content = text_content[1:]
                        # 移除所有换行符和多余的空格
                        text_content = text_content.replace('\n', ' ').replace('\r', '')
                        text_content = ' '.join(text_content.split())
                        
                        logger.info(f"Processed text content: {repr(text_content)}")
                        parsed_data = json.loads(text_content)
                    except Exception as e:
                        logger.error(f"Failed to fix JSON: {str(e)}")
                        logger.error(f"Final content that failed to parse: {repr(text_content)}")
                        return False

                logger.info(f"Parsed JSON successfully: {json.dumps(parsed_data, ensure_ascii=False, indent=2)}")
            except Exception as e:
                logger.error(f"JSON parsing failed: {str(e)}")
                logger.error(f"Content that failed to parse: {text_content}")
                error_msg = f"JSON parsing failed: {str(e)}"
                status_manager.record_error('llm_judge', error_msg)
                return False

            # 3. 提取分值和类别
            tags_str = parsed_data.get("标签", "") or ""
            tags = self.process_tags(tags_str)
            category_str = parsed_data.get("类型", "") or ""
            categorys = self.process_tags(category_str)
            # 提取分类
            reason = parsed_data.get("播报内容", "")  # 提取原因
            stars = parsed_data.get("评分", "")  # 提取星级

            # 记录提取的数据
            logger.info(f"Extracted data for post {self.post_id}:")
            logger.info(f"Tags: {tags}")
            logger.info(f"Categories: {categorys}")
            logger.info(f"Reason: {reason}")
            logger.info(f"Stars: {stars}")

            # 使用 TagSaver 保存数据
            with SessionLocal() as db:
                tag_saver = TagSaver(db, post_id=self.post_id, tags=tags, categorys=categorys, reason=reason, stars=stars)
                tag_saver.save()

            return True
        else:
            logger.error(f"Failed to run workflow. Status code: {response.status_code}")
            logger.error(f"Response: {response.text}")
            error_msg = f"Failed to run workflow. Status code: {response.status_code}"
            status_manager.record_error('llm_judge', error_msg)

        return False

    def process_tags(self, tags_input):
        if isinstance(tags_input, list):
            # 如果输入是列表，直接清理并返回
            return [tag.strip("<>").strip() for tag in tags_input if tag.strip("<>").strip()]
        elif isinstance(tags_input, str):
            # 如果输入是字符串，先分割再清理
            return [tag.strip("<>").strip() for tag in tags_input.split(",") if tag.strip("<>").strip()]
        else:
            # 对于其他类型，返回空列表或者抛出异常
            return []


if __name__ == "__main__":
    post_id = 2
    url = ""
    judge_url = "http://192.168.222.129/v1/workflows/run"
    content = "我是一只鸡"
    api_key = "app-5E0QBeP9b6PhJLONh9dUzHKu"
    llm_with_jina = LLMWithOutJina(post_id,  content, url)
    llm_with_jina.run_workflow()

